<template>
  <DeviceCard :title="title" :status="statusText" custom-class="servo-card">
    <div class="servo-control">
      <el-slider
        v-model="currentAngle"
        :min="0"
        :max="180"
        :step="1"
        @change="updateServoAngle"
        :disabled="isLoading"
        class="custom-slider"
      />
      <div class="angle-display">{{ currentAngle }}°</div>
      <el-button @click="updateServoAngle" type="primary" :loading="isLoading">
        设置角度
      </el-button>
    </div>
  </DeviceCard>
</template>

<script>
import DeviceCard from './DeviceCard.vue';
import socket from '../socket';  // 引入封装的socket模块

export default {
  name: 'ServoControl',
  components: {
    DeviceCard
  },
  props: {
    deviceId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      title: '舵机控制',
      currentAngle: 90, // 初始角度为90度
      isLoading: false
    };
  },
  computed: {
    statusText() {
      return `当前角度: ${this.currentAngle}°`;
    }
  },
  created() {
    // 订阅舵机状态更新
    this.unsubscribe = socket.subscribeToDeviceUpdates('servo', (data) => {
      // 只处理当前设备的更新
      if (data.deviceId === this.deviceId) {
        this.currentAngle = parseInt(data.angle);

      }
    });

    // 注册设备
    socket.socket.emit('register-device', {
      id: this.deviceId,
      type: 'servo'
    });
  },
  methods: {
    updateServoAngle() {
      this.isLoading = true;

      // 使用封装的socket方法发送命令
      socket.controlServo(this.currentAngle);

      // 模拟响应处理
      setTimeout(() => {
        this.isLoading = false;
        this.$message.success(`舵机已设置到 ${this.currentAngle}°`);
      }, 500);
    }
  },
  beforeDestroy() {
    // 取消订阅
    if (this.unsubscribe) {
      this.unsubscribe();
    }
  }
};
</script>

<style scoped>
.servo-control {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 20px;
}

.angle-display {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

/* 添加自定义滑块样式 */
.custom-slider {
  width: 100%;
  max-width: 500px; /* 设置最大宽度 */
}

.servo-card {
  width: 100%;
  max-width: 600px; /* 增加卡片最大宽度 */
  margin: 0 auto;
}
</style>